/** Request 网络请求工具 更详细的 api 文档: https://github.com/umijs/umi-request */
import { extend } from 'umi-request';
import { notification } from 'antd';
import { getStore } from '@/utils/utils';
import { history } from 'umi';

// 根据状态码status，抛出对应的错误提示
const codeMessage = {
  403: '找不到该资源',
  504: '服务器发生错误，请检查服务器。',
};
/** 异常处理程序 */

const statusErrorHandler = (error) => {
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  } else if (!response && error.name === 'CODE_ERROR') {
    throw error;
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
    throw error;
  }

  return response;
};

const codeErrorHandler = (resBody, res) => {
  notification.error({
    message: `请求错误code(${resBody.code}): ${res.url}`,
    description: `${resBody.msg}`,
  });
  console.error('code error:', resBody);
}

/** 配置request请求时的默认参数 */
const request = extend({
  errorHandler: statusErrorHandler,
  // 默认错误处理
  // credentials: 'include', // 默认请求是否带上cookie
});

request.interceptors.request.use((url, options) => {
  const token = getStore({
    name: 'USER_TOKEN'
  });
  const headers = {};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  return {
    options: {
      ...options,
      headers,
    }
  };
});

request.interceptors.response.use(async (response, options) => {
  const resBody = await response.clone().json();
  if (typeof resBody.code !== 'undefined') {
    // 标准格式处理
    switch(resBody.code) {
      case 1:
        // 成功返回
        return response;
      case 5000:
        // 登录失败
        return response;
      case 5001:
        // 跳转登录页
        history.replace({
          pathname: '/admin/user/login'
        })
        return response;
      default:
        // 统一处理code错误
        codeErrorHandler(resBody, response);
        const err = new Error(`(code:${resBody.code})${resBody.msg}`);
        err.name = 'CODE_ERROR';
        throw err;
    }
    
  } 
  return response;
});
export default request;
